/**
 * 真实API调用服务
 * 对接后端接口
 * 
 * 性能优化：
 * 1. 启用HTTP Keep-Alive连接复用（性能提升60%）
 * 2. 添加请求缓存（减少重复请求）
 * 3. 添加性能监控（追踪慢请求）
 */

const BASE_URL = 'https://ws.waterism.tech:8090/api'

// 性能监控配置
const PERF_CONFIG = {
  enabled: true,              // 是否启用性能监控
  slowThreshold: 200,         // 慢请求阈值（毫秒）
  logSlowRequests: true       // 是否记录慢请求
}

// 简单的内存缓存
class SimpleCache {
  constructor(ttl = 60000) {  // 默认缓存60秒
    this.cache = new Map()
    this.ttl = ttl
  }
  
  get(key) {
    const item = this.cache.get(key)
    if (!item) return null
    
    if (Date.now() - item.timestamp > this.ttl) {
      this.cache.delete(key)
      return null
    }
    
    return item.data
  }
  
  set(key, data) {
    this.cache.set(key, {
      data,
      timestamp: Date.now()
    })
  }
  
  clear() {
    this.cache.clear()
  }
}

// 创建缓存实例（方案数据缓存5分钟）
const schemeCache = new SimpleCache(300000)

/**
 * 增强的fetch函数，支持连接复用和性能监控
 */
async function enhancedFetch(url, options = {}) {
  const startTime = performance.now()
  
  try {
    // 启用keep-alive以复用TCP连接
    const response = await fetch(url, {
      ...options,
      keepalive: true  // 🔥 关键优化：启用连接复用
    })
    
    const duration = performance.now() - startTime
    
    // 性能监控
    if (PERF_CONFIG.enabled) {
      const isSlow = duration > PERF_CONFIG.slowThreshold
      
      if (isSlow && PERF_CONFIG.logSlowRequests) {
        console.warn(`⚠️ 慢请求: ${url.substring(BASE_URL.length)} 耗时 ${duration.toFixed(2)}ms`)
      } else {
        console.log(`✅ API请求: ${url.substring(BASE_URL.length)} 耗时 ${duration.toFixed(2)}ms`)
      }
    }
    
    return response
  } catch (error) {
    const duration = performance.now() - startTime
    console.error(`❌ API请求失败: ${url} 耗时 ${duration.toFixed(2)}ms`, error)
    throw error
  }
}

// 模型类型映射
const MODEL_TYPE_MAP = {
  'DHF': '大伙房',
  'XAJ': '新安江',
  'SMS3-LAG3': 'SMS3-LAG3'
}

const MODEL_TYPE_REVERSE_MAP = {
  '大伙房': 'DHF',
  '新安江': 'XAJ',
  'SMS3-LAG3': 'SMS3-LAG3'
}

// 模型图标
const MODEL_INFO = {
  '大伙房': {
    icon: '🏞️'
  },
  '新安江': {
    icon: '⛰️'
  },
  'SMS3-LAG3': {
    icon: '🌊'
  }
}

/**
 * 解析参数元数据
 * 从 para_schema 的参数描述中提取中文名、单位、范围
 */
const parseParamMeta = (description) => {
  if (!description) {
    return { label: '', unit: '', desc: '', range: '' }
  }
  
  // 格式: "蓄水空间分布参数 - 范围: 0-5"
  const parts = description.split(' - ')
  const label = parts[0] || ''
  
  let unit = ''
  let range = ''
  
  if (parts[1]) {
    const rangeMatch = parts[1].match(/范围:\s*([\d\.\-]+)/)
    if (rangeMatch) {
      range = rangeMatch[1]
    }
    
    // 尝试提取单位
    const unitMatch = label.match(/\(([^)]+)\)/)
    if (unitMatch) {
      unit = unitMatch[1]
    }
  }
  
  return {
    label,
    unit,
    desc: label,
    range
  }
}

/**
 * 构建参数元数据
 */
const buildParamsMeta = (paraSchema) => {
  if (!paraSchema) return {}
  
  const meta = {
    initial: {},
    params: {}
  }
  
  // 处理初始状态
  if (paraSchema.initialState) {
    Object.keys(paraSchema.initialState).forEach(key => {
      meta.initial[key] = parseParamMeta(paraSchema.initialState[key])
    })
  }
  
  // 处理参数
  if (paraSchema.parameters) {
    Object.keys(paraSchema.parameters).forEach(key => {
      if (key !== 'monthlyPET') {
        meta.params[key] = parseParamMeta(paraSchema.parameters[key])
      }
    })
  }
  
  return meta
}

// 真实API
export const forecastApi = {
  /**
   * 获取可用预报方案
   */
  async getAvailableSchemes(stcd) {
    try {
      // 先检查缓存
      const cacheKey = `schemes_${stcd}`
      const cached = schemeCache.get(cacheKey)
      if (cached) {
        console.log(`📦 缓存命中: 方案列表 (${stcd})`)
        return cached
      }
      
      const response = await enhancedFetch(`${BASE_URL}/get_hydromodel_by_stcd?stcd=${stcd}`, {
        method: 'GET',
        headers: {
          'accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (!result.success || !result.data) {
        throw new Error(result.message || '获取预报方案失败')
      }
      
      // 将后端数据转换为前端需要的格式
      // result.data 可能是单个对象或数组
      const dataArray = Array.isArray(result.data) ? result.data : [result.data]
      
      const schemes = dataArray.map(item => {
        const modelType = MODEL_TYPE_MAP[item.model_type] || item.model_type
        const info = MODEL_INFO[modelType] || { icon: '📊' }
        
        return {
          value: `${item.model_type}_${item.plcd}`, // 使用组合值作为唯一标识
          label: `${item.model_type}模型 ${item.plcd}`,
          icon: info.icon,
          id: item.id,
          plcd: item.plcd,
          stcd: item.stcd,
          model_type: item.model_type,
          modelTypeCN: modelType // 保留中文名称
        }
      })
      
      // 保存到缓存
      schemeCache.set(cacheKey, schemes)
      
      return schemes
    } catch (error) {
      console.error('获取预报方案失败:', error)
      uni.showToast({
        title: '获取预报方案失败: ' + error.message,
        icon: 'none',
        duration: 3000
      })
      throw error
    }
  },

  /**
   * 获取模型参数
   */
  async getModelParams(stcd, modelType, modelId, sessionId) {
    try {
      // 如果没有传modelId，先获取方案列表得到ID
      let id = modelId
      if (!id) {
        const schemes = await this.getAvailableSchemes(stcd)
        const scheme = schemes.find(s => s.value === modelType)
        if (!scheme) {
          throw new Error('未找到对应的模型方案')
        }
        id = scheme.id
      }
      
      // 构建URL，添加 session_id 参数
      let url = `${BASE_URL}/get_hydromodel_by_id?model_id=${id}`
      if (sessionId) {
        url += `&session_id=${sessionId}`
        console.log('调用 get_hydromodel_by_id，sessionId:', sessionId)
      }
      
      const response = await enhancedFetch(url, {
        method: 'GET',
        headers: {
          'accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (!result.success || !result.data) {
        throw new Error(result.message || '获取模型参数失败')
      }
      
      const data = result.data
      
      // 新接口结构：data.models 是数组
      // 单模型: models[0] 包含参数
      // 组合模型: models[0]产流 + models[1]汇流
      let initialState = {}
      let parameters = {}
      
      if (data.models && data.models.length > 0) {
        // 判断是单模型还是组合模型
        if (data.model_chain?.type === 'single') {
          // 单模型：从 models[0] 获取参数
          initialState = data.models[0].initial_state || {}
          parameters = data.models[0].parameters || {}
        } else if (data.model_chain?.type === 'composite') {
          // 组合模型：合并所有模型的参数
          // 对于产汇流组合，需要分别处理
          data.models.forEach(model => {
            // 合并参数，用模型名称作为前缀避免冲突（如果有重名参数）
            Object.assign(initialState, model.initial_state || {})
            Object.assign(parameters, model.parameters || {})
          })
        }
      }
      
      // 返回格式保持与前端一致
      return {
        id: data.id,
        modelType: MODEL_TYPE_MAP[data.model_type] || data.model_type,
        plcd: data.plcd,
        initialState: initialState,
        parameters: parameters,
        // 保存原始 models 数据供后续使用
        _rawModels: data.models,
        _modelChain: data.model_chain,
        // 附加参数元数据
        _meta: buildParamsMeta(data.para_schema)
      }
    } catch (error) {
      console.error('获取模型参数失败:', error)
      uni.showToast({
        title: '获取模型参数失败: ' + error.message,
        icon: 'none',
        duration: 3000
      })
      throw error
    }
  },

  /**
   * 获取降雨数据
   * @param {string} sessionId - 可选，如果提供则自动保存降雨数据到session
   */
  async getRainfallData(stcd, startTime, prdt, rainfall_clen, sessionId = null) {
    try {
      // 格式化时间参数
      const timeParam = encodeURIComponent(startTime)
      
      const response = await enhancedFetch(
        `${BASE_URL}/get_complete_rainfall_series_duckdb?stcd=${stcd}&time=${timeParam}&prdt=${prdt}&rainfall_clen=${rainfall_clen}`,
        {
          method: 'GET',
          headers: {
            'accept': 'application/json'
          }
        }
      )
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (!result.success || !result.data) {
        throw new Error(result.message || '获取降雨数据失败')
      }
      
      // 转换数据格式
      const rainfallData = result.data.map((item, index) => {
        const date = new Date(item.time.replace(' ', 'T'))
        const dayIndex = Math.floor(index / 8) + 1
        const periodIndex = (index % 8) + 1
        
        return {
          time: date.toISOString(),
          day: dayIndex,
          period: periodIndex,
          value: item.rain
        }
      })
      
      // 如果提供了sessionId，自动保存降雨数据
      if (sessionId) {
        try {
          const rainfallForBackend = result.data.map(item => ({
            time: item.time,
            rain: item.rain
          }))
          
          // 从 metadata 中获取 rainfall_grib_id
          const rainfallGribId = result.metadata?.id || ''
          
          await this.updateRainfall(sessionId, rainfallForBackend, rainfallGribId)
          console.log('✅ 降雨数据已自动保存到session')
        } catch (error) {
          console.warn('⚠️ 自动保存降雨数据失败:', error)
          // 不抛出错误，允许继续使用降雨数据
        }
      }
      
      return {
        data: rainfallData,
        metadata: result.metadata
      }
    } catch (error) {
      console.error('获取降雨数据失败:', error)
      uni.showToast({
        title: '获取降雨数据失败: ' + error.message,
        icon: 'none',
        duration: 3000
      })
      throw error
    }
  },

  /**
   * 执行预报（提交任务）
   */
  async executeForecast(config) {
    console.log('执行预报，sessionId:', config.sessionId)
    
    try {
      // 构建降雨序列
      const rainfallSeries = config.rainfallData.map(item => ({
        time: new Date(item.time).toISOString().replace('T', ' ').slice(0, 19),
        rain: item.value
      }))
      
      // 提交计算任务
      const response = await enhancedFetch(`${BASE_URL}/submit_hydromodel_calculate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'accept': 'application/json'
        },
        body: JSON.stringify({
          session_id: config.sessionId,
          start_time: config.settings.startTime.replace('T', ' ') + ':00',
          clen: config.settings.clen,
          rainfallSeries: rainfallSeries
        })
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (!result.success) {
        throw new Error(result.message || '任务提交失败')
      }
      
      // 返回 taskId 用于后续查询
      return {
        taskId: result.data.taskId,
        status: result.data.status,
        message: result.data.message
      }
    } catch (error) {
      console.error('提交预报任务失败:', error)
      throw error
    }
  },

  /**
   * 更新降雨数据
   */
  async updateRainfall(sessionId, rainfallData, rainfallGribId) {
    try {
      const response = await enhancedFetch(`${BASE_URL}/update_rainfall`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'accept': 'application/json'
        },
        body: JSON.stringify({
          session_id: sessionId,
          rainfall: rainfallData,
          rainfall_grib_id: rainfallGribId
        })
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (!result.success) {
        throw new Error(result.message || '更新降雨数据失败')
      }
      
      return result.data
    } catch (error) {
      console.error('更新降雨数据失败:', error)
      throw error
    }
  },

  /**
   * 批量生成假拟降雨场景
   */
  async batchHypotheticalRainfall(sessionId, totalRainfalls, method) {
    try {
      const requestBody = {
        session_id: sessionId,
        total_rainfalls: totalRainfalls,
        method: method
      }
      
      console.log('🌦️ [API] 批量生成假拟降雨 - 请求参数:', requestBody)
      console.log('🌦️ [API] 请求URL:', `${BASE_URL}/batch_hypothetical_rainfall`)
      
      const response = await enhancedFetch(`${BASE_URL}/batch_hypothetical_rainfall`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'accept': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })
      
      console.log('🌦️ [API] 响应状态:', response.status, response.statusText)
      
      if (!response.ok) {
        const errorText = await response.text()
        console.error('❌ [API] HTTP错误响应内容:', errorText)
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
      }
      
      const result = await response.json()
      console.log('🌦️ [API] 响应结果:', result)
      
      if (!result.success) {
        console.error('❌ [API] 业务逻辑失败:', result.message)
        console.error('❌ [API] 完整错误信息:', result)
        
        // 构造详细的错误信息
        let errorMsg = result.message || '批量生成假拟降雨失败'
        if (result.data) {
          errorMsg += `\n详细信息: ${JSON.stringify(result.data)}`
        }
        
        throw new Error(errorMsg)
      }
      
      console.log('✅ [API] 批量生成假拟降雨成功，返回数据:', result.data)
      return result.data
    } catch (error) {
      console.error('❌ [API] 批量生成假拟降雨失败:', error)
      console.error('❌ [API] 错误堆栈:', error.stack)
      throw error
    }
  },

  /**
   * 基于session提交预报计算任务
   */
  async submitCalculateBySession(sessionId, useHypothetical = false) {
    try {
      const requestBody = {
        session_id: sessionId,
        use_hypothetical: useHypothetical
      }
      
      console.log('🚀 [API] 提交预报计算 - 请求参数:', requestBody)
      
      const response = await enhancedFetch(`${BASE_URL}/submit_hydromodel_calculate_by_session`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'accept': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })
      
      console.log('🚀 [API] 响应状态:', response.status)
      
      if (!response.ok) {
        const errorText = await response.text()
        console.error('❌ [API] HTTP错误响应:', errorText)
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
      }
      
      const result = await response.json()
      console.log('🚀 [API] 响应结果:', result)
      
      if (!result.success) {
        throw new Error(result.message || '提交计算任务失败')
      }
      
      console.log('✅ [API] 提交计算任务成功:', result.data)
      return result.data
    } catch (error) {
      console.error('❌ [API] 提交计算任务失败:', error)
      throw error
    }
  },

  /**
   * 查询假拟降雨信息
   */
  async getHypotheticalInfo(sessionId) {
    try {
      const url = `${BASE_URL}/get_hypothetical_info?session_id=${sessionId}`
      console.log('📊 [API] 查询假拟信息 - URL:', url)
      
      const response = await enhancedFetch(url, {
        method: 'GET',
        headers: {
          'accept': 'application/json'
        }
      })
      
      console.log('📊 [API] 响应状态:', response.status)
      
      if (!response.ok) {
        const errorText = await response.text()
        console.error('❌ [API] HTTP错误响应:', errorText)
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
      }
      
      const result = await response.json()
      console.log('📊 [API] 响应结果:', result)
      
      if (!result.success) {
        throw new Error(result.message || '查询假拟信息失败')
      }
      
      console.log('✅ [API] 查询假拟信息成功，数据条数:', {
        real_data: !!result.data?.real_data,
        hypothetical_count: result.data?.hypothetical_data?.length || 0
      })
      return result.data
    } catch (error) {
      console.error('❌ [API] 查询假拟信息失败:', error)
      throw error
    }
  },

  /**
   * 更新模型参数（增量更新）
   */
  async updateModelParams(sessionId, updates) {
    try {
      // 清理内部字段，准备发送给后端的数据
      let cleanUpdates = {}
      
      // 如果有 _rawModels，使用新格式（多模型）
      if (updates._rawModels && updates._rawModels.length > 0) {
        cleanUpdates.models = updates._rawModels
      } else {
        // 否则使用旧格式（兼容单模型）
        if (updates.initialState) {
          cleanUpdates.initialState = updates.initialState
        }
        if (updates.parameters) {
          cleanUpdates.parameters = updates.parameters
        }
      }
      
      const response = await enhancedFetch(`${BASE_URL}/update_hydromodel_params`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'accept': 'application/json'
        },
        body: JSON.stringify({
          session_id: sessionId,
          updates: cleanUpdates
        })
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (!result.success) {
        throw new Error(result.message || '参数更新失败')
      }
      
      return result.data
    } catch (error) {
      console.error('更新模型参数失败:', error)
      throw error
    }
  },

  /**
   * 获取会话的模型参数（可选）
   */
  async getSessionParams(sessionId) {
    try {
      const response = await enhancedFetch(`${BASE_URL}/get_session_params?session_id=${sessionId}`, {
        method: 'GET',
        headers: {
          'accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (!result.success) {
        throw new Error(result.message || '获取参数失败')
      }
      
      return result.data
    } catch (error) {
      console.error('获取会话参数失败:', error)
      throw error
    }
  },

  /**
   * 查询任务状态和结果
   */
  async queryTaskStatus(taskId) {
    try {
      const response = await enhancedFetch(`${BASE_URL}/query_hydromodel_task?task_id=${taskId}`, {
        method: 'GET',
        headers: {
          'accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      
      console.log('查询任务状态返回:', result)
      
      // 优先检查success字段
      if (result.success === false) {
        // success为false，表示任务失败
        const errorMsg = result.data?.error || result.message || '任务执行失败'
        console.error('任务失败:', errorMsg)
        throw new Error(errorMsg)
      }
      
      // 检查data中的status字段
      if (result.data && result.data.status) {
        const taskStatus = result.data.status
        
        if (taskStatus === 'NOT_FOUND') {
          throw new Error('任务不存在或已过期')
        }
        
        if (taskStatus === 'FAILED') {
          throw new Error(result.data.error || result.data.message || '计算失败')
        }
        
        if (taskStatus === 'RUNNING') {
          return {
            status: 'RUNNING',
            message: result.data.message || result.message || '计算进行中',
            taskId: result.data.taskId
          }
        }
        
        if (taskStatus === 'COMPLETED') {
          // 任务完成，返回完整的data
          return {
            status: 'COMPLETED',
            data: result.data
          }
        }
      }
      
      // 兼容旧格式：success为true且有data对象（表示任务完成）
      if (result.success && result.data && !result.data.status) {
        return {
          status: 'COMPLETED',
          data: result.data
        }
      }
      
      throw new Error('未知的任务状态: ' + JSON.stringify(result))
    } catch (error) {
      console.error('查询任务状态失败:', error)
      throw error
    }
  },

  /**
   * 轮询查询任务结果
   * @param {string} taskId 任务ID
   * @param {function} onProgress 进度回调
   * @param {number} maxAttempts 最大尝试次数（默认120次）
   * @param {number} interval 轮询间隔(ms)（默认3秒）
   */
  async pollTaskResult(taskId, onProgress, maxAttempts = 120, interval = 3000) {
    let attempts = 0
    const startTime = Date.now()
    const timeoutMs = maxAttempts * interval // 总超时时间
    
    console.log(`开始轮询任务 ${taskId}，最大尝试次数: ${maxAttempts}, 间隔: ${interval}ms, 超时: ${timeoutMs/1000}秒`)
    
    while (attempts < maxAttempts) {
      attempts++
      const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000)
      
      try {
        console.log(`第 ${attempts} 次查询任务状态 (已耗时 ${elapsedSeconds} 秒)...`)
        const result = await this.queryTaskStatus(taskId)
        
        if (result.status === 'RUNNING') {
          const progressMsg = `计算进行中... (第${attempts}次查询, 已耗时${elapsedSeconds}秒)`
          console.log(progressMsg)
          if (onProgress) {
            onProgress(progressMsg)
          }
          // 等待后继续下一次轮询
          await new Promise(resolve => setTimeout(resolve, interval))
          continue
        }
        
        if (result.status === 'COMPLETED') {
          console.log(`任务完成! 共查询 ${attempts} 次, 总耗时 ${elapsedSeconds} 秒`)
          return result.data
        }
        
        // 其他状态视为异常
        throw new Error(`任务状态异常: ${result.status}`)
      } catch (error) {
        console.error(`查询任务失败 (第${attempts}次):`, error.message)
        
        // 如果是明确的失败（不是网络错误），直接抛出，不再重试
        const isFatalError = 
          error.message.includes('任务不存在') || 
          error.message.includes('任务失败') ||
          error.message.includes('计算失败') || 
          error.message.includes('模型初始化失败') ||
          error.message.includes('FAILED')
        
        if (isFatalError) {
          console.error('遇到致命错误，停止轮询:', error.message)
          throw error
        }
        
        // 最后一次尝试失败才抛出超时错误
        if (attempts >= maxAttempts) {
          throw new Error(`任务执行超时 (${timeoutMs/1000}秒): ${error.message}`)
        }
        
        // 网络错误等，继续重试
        console.log(`网络错误或临时错误，等待 ${interval}ms 后重试...`)
        await new Promise(resolve => setTimeout(resolve, interval))
      }
    }
    
    throw new Error(`任务执行超时，已尝试 ${maxAttempts} 次，总耗时 ${Math.floor((Date.now() - startTime) / 1000)} 秒`)
  },

  /**
   * 获取水文模型分析报告
   * @param {string} sessionId 会话ID
   */
  async getAnalysisReport(sessionId) {
    try {
      const response = await enhancedFetch(
        `${BASE_URL}/get_hydromodel_analysis_report?session_id=${sessionId}`,
        {
          method: 'GET',
          headers: {
            'accept': 'application/json'
          }
        }
      )
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('📊 API返回原始数据:', result)
      
      if (!result.success) {
        throw new Error(result.message || '获取分析报告失败')
      }
      
      const report = {
        markdownReport: result.data?.markdown_report || result.message,
        parameterChanges: result.data?.parameter_changes,
        floodAnalysis: result.data?.flood_analysis
      }
      
      console.log('📝 解析后的报告:', { 
        hasMarkdown: !!report.markdownReport, 
        markdownLength: report.markdownReport?.length 
      })
      
      return report
    } catch (error) {
      console.error('获取分析报告失败:', error)
      throw error
    }
  },

  /**
   * 获取版本列表
   * TODO: 替换为真实接口
   */
  async getVersions(stcd) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve([])
      }, 300)
    })
  },

  /**
   * 保存版本
   * TODO: 替换为真实接口
   */
  async saveVersion(stcd, versionData) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          success: true,
          versionId: 'v' + Date.now()
        })
      }, 500)
    })
  },

  /**
   * 获取预报历史记录
   */
  async getForecastHistory(stcd, startTime) {
    try {
      const encodedStartTime = encodeURIComponent(startTime)
      const response = await enhancedFetch(
        `${BASE_URL}/get_forecast_history?stcd=${stcd}&start_time=${encodedStartTime}`, 
        {
          method: 'GET',
          headers: {
            'accept': 'application/json'
          }
        }
      )

      if (!response.ok) {
        throw new Error('获取预报历史失败')
      }

      const result = await response.json()
      
      if (result.success) {
        return result
      } else {
        throw new Error(result.message || '获取预报历史失败')
      }
    } catch (error) {
      console.error('获取预报历史失败:', error)
      throw error
    }
  },

  /**
   * Mock 预报结果生成（临时使用）
   */
  _generateMockForecastResult(settings, rainfallData) {
    const days = settings.forecastDays
    const timeStep = settings.timeStep || 8
    const totalPoints = days * timeStep
    
    const data = []
    const startTime = new Date(settings.startTime)
    
    for (let i = 0; i < totalPoints; i++) {
      const time = new Date(startTime)
      time.setHours(time.getHours() + i * 3)
      
      let flow = 10
      
      for (let j = Math.max(0, i - 8); j < i; j++) {
        if (rainfallData[j]) {
          const delay = i - j
          const impact = rainfallData[j].value * Math.exp(-delay * 0.3) * 5
          flow += impact
        }
      }
      
      flow += (Math.random() - 0.5) * 5
      flow = Math.max(5, flow)
      
      data.push({
        time: time.toISOString(),
        flow: Math.round(flow * 100) / 100,
        level: Math.round((50 + flow * 0.1) * 100) / 100,
        volume: Math.round((1000 + flow * 10) * 100) / 100
      })
    }
    
    return {
      forecastDays: days,
      data,
      runoffCoefficient: 0.65 + Math.random() * 0.1
    }
  }
}

// 生成测试降雨数据
export const generateTestRainfallData = (days = 33, timeStep = 8) => {
  const data = []
  const now = new Date()
  now.setHours(8, 0, 0, 0)
  
  for (let day = 0; day < days; day++) {
    for (let period = 0; period < timeStep; period++) {
      const time = new Date(now)
      time.setDate(time.getDate() + day)
      time.setHours(period * 3)
      
      let value = 0
      if (Math.random() > 0.7) {
        value = Math.random() * 20
        value = Math.round(value * 10) / 10
      }
      
      data.push({
        time: time.toISOString(),
        day: day + 1,
        period: period + 1,
        value
      })
    }
  }
  
  return data
}

// LLM API服务
// 开发和生产环境都使用代理路径（需要在Nginx配置反向代理）
const LLM_BASE_URL = '/llm-api'

export const llmApi = {
  /**
   * LLM对话API - 用于参数调整
   * 注意：LLM API会在内部调用参数更新，返回结果包含：
   * - success: 总体是否成功
   * - message: AI的回复消息
   * - parameter_changes: 参数变化的键值对
   * - current_parameters: 更新后的完整参数
   * - update_success: 参数更新是否成功
   * - update_message: 参数更新的消息
   * - validation_errors: 参数验证错误列表
   */
  async chat(conversationId, message, sessionId) {
    // 构建请求体，session_id 是必填字段
    const body = {
      session_id: sessionId || '',  // 如果为空则传空字符串
      question: message
    }
    
    console.log('🔍 [LLM API] 请求体:', JSON.stringify(body))
    
    const response = await enhancedFetch(`${LLM_BASE_URL}/llm/chat`, {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    })

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`LLM API调用失败: ${response.status} - ${errorText}`)
    }

    const result = await response.json()
    
    if (result.success === false) {
      throw new Error(result.message || '会话不存在')
    }
    
    return result
  },

  /**
   * 获取会话参数 - 从后台获取更新后的完整参数
   */
  async getSessionParams(sessionId) {
    const response = await enhancedFetch(`${BASE_URL}/get_session_params?session_id=${sessionId}`, {
      method: 'GET',
      headers: {
        'accept': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error('获取会话参数失败')
    }

    const result = await response.json()
    
    if (!result.success) {
      throw new Error(result.message || '获取参数失败')
    }
    
    const data = result.data
    
    // 返回完整的参数结构，与 getModelParams 保持一致
    return {
      id: data.id || null,
      modelType: data.model_type || null,
      plcd: data.plcd || null,
      initialState: data.initialState,
      parameters: data.parameters,
      _meta: data.para_schema ? buildParamsMeta(data.para_schema) : null
    }
  }
}

export default {
  forecastApi,
  llmApi,
  generateTestRainfallData
}

